package org.jeecg.modules.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.customer.entity.BusCustomer;
import org.jeecg.modules.customer.service.IBusCustomerService;
import org.jeecg.modules.demo.points.entity.BusVipPointDetail;
import org.jeecg.modules.demo.points.service.IBusVipPointDetailService;
import org.jeecg.modules.demo.totalpoints.entity.BusVipPoint;
import org.jeecg.modules.demo.totalpoints.service.IBusVipPointService;
import org.jeecg.modules.message.wechat.FuWuHaoMessageService;
import org.jeecg.modules.order.entity.BusOrder;
import org.jeecg.modules.order.entity.BusOrderItem;
import org.jeecg.modules.order.entity.BusOrderPics;
import org.jeecg.modules.order.mapper.BusOrderItemMapper;
import org.jeecg.modules.order.mapper.BusOrderMapper;
import org.jeecg.modules.order.mapper.BusOrderPicsMapper;
import org.jeecg.modules.order.service.IBusOrderService;
import org.jeecg.modules.ordercommon.service.OrderPointsService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2021-07-13
 * @Version: V1.0
 */
@Service
public class BusOrderServiceImpl extends ServiceImpl<BusOrderMapper, BusOrder> implements IBusOrderService {

    @Autowired
    private BusOrderMapper busOrderMapper;
    @Autowired
    private BusOrderItemMapper busOrderItemMapper;
    @Autowired
    private BusOrderPicsMapper busOrderPicsMapper;
    @Autowired
    private OrderPointsService orderPointsService;
    @Autowired
    private IBusCustomerService busCustomerService;

    @Autowired
    private IBusVipPointService vipPointService;

    @Autowired
    private IBusCustomerService customerService;


    @Autowired
    private IBusVipPointDetailService detailService;

    @Autowired
    private FuWuHaoMessageService fuWuHaoMessageService;

    @Override
    @Transactional
    public void saveMain(BusOrder busOrder, List<BusOrderItem> busOrderItemList, List<BusOrderPics> busOrderPicsList) {
        busOrder.setStatus(1);
        if (busOrder.getAmount() == null) {
            busOrder.setAmount(new BigDecimal(0.0));
        }
        if (busOrder.getPoints() == null) {
            busOrder.setPoints(0);
        }
        if (busOrder.getPoints() > 0) {
            updatePointsByOrder(null, busOrder, 1);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        busOrder.setSysOrgCode(sysUser.getOrgCode());
        busOrderMapper.insert(busOrder);
        if (busOrderItemList != null && busOrderItemList.size() > 0) {
            for (BusOrderItem entity : busOrderItemList) {
                //外键设置
                entity.setOrderId(busOrder.getId());
                busOrderItemMapper.insert(entity);
            }
        }
        if (busOrderPicsList != null && busOrderPicsList.size() > 0) {
            for (BusOrderPics entity : busOrderPicsList) {
                //外键设置
                entity.setOrderId(busOrder.getId());
                busOrderPicsMapper.insert(entity);
            }
        }
        //根据加个修改积分
//        updatePointsByOrder(busOrder, 1);

        //解锁积分，如果没有解锁
        String userId = sysUser.getId();
        Map<String,Object> countP = new HashMap<>();
        countP.put("cusId", busOrder.getCusId());
        int samcount = busOrderMapper.selectYangbenCount(countP);
        if (samcount >= 10) {
            freezPoints(sysUser.getId());
        }
        //推送订单消息到运营人员
        fuWuHaoMessageService.SendNewOrderWxMsg(busOrder);
    }

    private void freezPoints(String id) {
        LambdaQueryWrapper<BusVipPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusVipPoint::getUserId, id);
        BusVipPoint busVipPoint = vipPointService.getOne(wrapper);
        if (1 == busVipPoint.getFreeRegPoint()) {
            return;
        } else {
            busVipPoint.setUseablePoints(busVipPoint.getUseablePoints() + 300);
            vipPointService.updateById(busVipPoint);
        }
    }

    @Override
    @Transactional
    public void updateMain(BusOrder busOrder, List<BusOrderItem> busOrderItemList, List<BusOrderPics> busOrderPicsList) {

        //检查积分是否有变化
        BusOrder tBusorder = this.baseMapper.selectById(busOrder.getId());
        if (tBusorder.getPoints() != busOrder.getPoints()) {
            updatePointsByOrder(tBusorder, busOrder, 1);
        }

        busOrderMapper.updateById(busOrder);
        //1.先删除子表数据
        busOrderItemMapper.deleteByMainId(busOrder.getId());
        busOrderPicsMapper.deleteByMainId(busOrder.getId());

        //2.子表数据重新插入
        if (busOrderItemList != null && busOrderItemList.size() > 0) {
            for (BusOrderItem entity : busOrderItemList) {
                //外键设置
                entity.setOrderId(busOrder.getId());
                busOrderItemMapper.insert(entity);
            }
        }
        if (busOrderPicsList != null && busOrderPicsList.size() > 0) {
            for (BusOrderPics entity : busOrderPicsList) {
                //外键设置
                entity.setOrderId(busOrder.getId());
                busOrderPicsMapper.insert(entity);
            }
        }
        //根据价格修改积分
        //删除之前的积分

        //添加新的积分
    }

    @Override
    @Transactional
    public void delMain(String id) {
        BusOrder order = busOrderMapper.selectById(id);
//        updatePointsByOrder(order, 2);
        busOrderItemMapper.deleteByMainId(id);
        busOrderPicsMapper.deleteByMainId(id);
        busOrderMapper.deleteById(id);
        //根据价格修改积分
//        updatePointsByOrder(order, 2);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            BusOrder order = busOrderMapper.selectById(id);
//            updatePointsByOrder(order, 2);
            busOrderItemMapper.deleteByMainId(id.toString());
            busOrderPicsMapper.deleteByMainId(id.toString());
            busOrderMapper.deleteById(id);

        }
    }

    private void updatePointsByOrder(BusOrder oleOrder, BusOrder order, Integer direction) {
//        BigDecimal price = order.getAmount();
//        Integer points = orderPointsService.calPoints(price.intValue(), order.getSampleNum(), direction);
//        String cusId = order.getCusId();
        Integer points = order.getPoints();
        BusCustomer busCustomer = busCustomerService.getById(order.getCusId());

        LambdaQueryWrapper<BusVipPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusVipPoint::getUserId, busCustomer.getSysUserId());
        BusVipPoint busVipPoint = vipPointService.getOne(wrapper);
        if (busVipPoint == null) {
            busVipPoint = new BusVipPoint();
            busVipPoint.setUserId(busCustomer.getSysUserId());
            busVipPoint.setPoints(points);
            vipPointService.save(busVipPoint);

        } else {
            if (null != oleOrder) {
                busVipPoint.setPoints(points + busVipPoint.getPoints() - oleOrder.getPoints());
                busVipPoint.setUseablePoints(points + busVipPoint.getUseablePoints() - oleOrder.getPoints());
            } else {
                busVipPoint.setPoints(points + busVipPoint.getPoints());
                busVipPoint.setUseablePoints(points +busVipPoint.getUseablePoints());
            }

            vipPointService.updateById(busVipPoint);
        }
        LambdaQueryWrapper<BusVipPointDetail> tDetailWrapper = new LambdaQueryWrapper<>();
        tDetailWrapper.eq(BusVipPointDetail::getOrderId, order.getId());
        detailService.remove(tDetailWrapper);
        BusVipPointDetail detail = new BusVipPointDetail();
        detail.setInOut(direction);
        detail.setUserId(busCustomer.getSysUserId());
        detail.setAmount(points);
        detail.setOrderId(order.getId());
        detail.setCreateTime(new Date());
        detail.setUserPhone(busCustomer.getCusTel());
        detailService.save(detail);

        //推送积分变动信息到客户端
        fuWuHaoMessageService.sendPointsMessage("wx7ac6ed39d0d2af6d", busCustomer.getOpenId(), detail, busVipPoint);
    }

    @Override
    public Map<Integer, Integer> countStatus(Map<String, Object> params) {

        return busOrderMapper.countStatus(params);
    }

    @Override
    public void modifyPrice(BigDecimal price, String busOrderId) {
        BusOrder busOrder = this.baseMapper.selectById(busOrderId);
        busOrder.setAmount(price);
        this.baseMapper.updateById(busOrder);
    }


    /**
     * 更新订单价格
     *
     * @param orderId
     * @param price
     */
//    public void updatePrice(String orderId, BigDecimal price) {
//        BusOrder busOrder = busOrderMapper.selectById(orderId);
//        busOrder.setPrice(price);
//        busOrderMapper.updateById(busOrder);
//        BusCustomer customer = customerService.getById(busOrder.getId());
//        LambdaQueryWrapper<BusVipPoint> pointsWrapper = new LambdaQueryWrapper<>();
//        pointsWrapper.eq(BusVipPoint::getUserId, customer.getSysUserId());
//        BusVipPoint vipPoint = vipPointService.getOne(pointsWrapper);
//        Integer direction = 1;
//        if (vipPoint != null) {
//            LambdaQueryWrapper<BusVipPointDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            detailLambdaQueryWrapper.eq(BusVipPointDetail::getOrderId, busOrder.getId());
//            List<BusVipPointDetail> details = detailService.list(detailLambdaQueryWrapper);
//            if (details != null && details.size() > 0) {
//                //统计明细积分
//                List<String> ids = new ArrayList<>();
//                Integer orderCountPoints = 0;
//                for (BusVipPointDetail detail : details) {
//                    orderCountPoints += detail.getAmount();
//                    ids.add(detail.getId());
//                    direction = detail.getInOut();
//                }
//                vipPoint.setPoints(vipPoint.getPoints() - orderCountPoints);
//                vipPointService.updateById(vipPoint);
//            }
//        }
//
//        //修改积分
////        updatePointsByOrder(busOrder, direction);
//    }


}
